using System;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
using BaseClass;

namespace WindowsApplication1
{
    public partial class Form4 : Form
    {
        public Form4()
        {
            InitializeComponent();
        }

        private void Form4_Load(object sender, EventArgs e)
        {
        }

        private void StartSendFile(string strHost, int iPort, string strFile)
        {
            SendFile sfFile = new SendFile(strHost, iPort, strFile, this.pbMain);
            pbMain.Value = 0;
            StartThread(new ThreadStart(sfFile.Send));
        }

        private void StartThread(ThreadStart target)
        {
            Thread doStep = new Thread(target);
            doStep.IsBackground = true;
            doStep.Start();
        }

        public class SendFile
        {
            private string Host;
            private int Port;
            private string FileToSend;
            private ProgressBar pbar;

            public SendFile(string strHost, int iPort, string strFile, ProgressBar pbMain)
            {
                Host = strHost;
                Port = iPort;
                FileToSend = strFile;
                pbar = pbMain;
            }

            public void Send()
            {
                Socket s = null;
                try
                {
                    s = CommunClass.ConnectToServer(Host, Port);
                    CommunClass.WriteCommandToSocket(s, "SENDFILE");
                    CommunClass.WriteCommandDescToSocket(s, "");
                    CommunClass.WriteFileToSocket(s, FileToSend, new CommunClass.OnSend(OnSendDrawProgress));
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
                finally
                {
                    if (s != null)
                        s.Close();
                }
            }

            public void OnSendDrawProgress(int iTotal, int iSending)
            {
                if (iTotal != pbar.Maximum)
                    pbar.Maximum = iTotal;
                pbar.Value = iSending;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            StartSendFile("localhost", 8000, "d:\\1.txt");
        }//end class
    }
}